<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    table {
      width: 230px;
      height: 180px;
      margin: 100px auto;
      text-align: center;
      border-collapse: collapse;
      border-spacing: 0;
      border: 1px solid gray;
    }

    thead tr {
      height: 30px;
      color: #fff;
      background-color: skyblue;
      border: 1px solid gray;
    }

    tbody td {
      text-align: center;
      border: 1px solid gray;
      padding-top: 4px;
      background-color: rgb(195, 191, 191);
    }
  </style>
</head>

<body>
  <table>
    <thead>
      <tr>
        <th><input type="checkbox" id="j_cbAll"></th>
        <th>商品</th>
        <th>价格</th>
      </tr>
    </thead>
    <tbody id="j_tb">
      <tr>
        <td><input type="checkbox"></td>
        <td>iPhone 4</td>
        <td>2000</td>
      </tr>
      <tr>
        <td><input type="checkbox"></td>
        <td>iPhone 7</td>
        <td>4000</td>
      </tr>
      <tr>
        <td><input type="checkbox"></td>
        <td>iPhone 11</td>
        <td>8000</td>
      </tr>
      <tr>
        <td><input type="checkbox"></td>
        <td>iPhone 8</td>
        <td>6000</td>
      </tr>
    </tbody>
  </table>
  <script>
    var j_cbAll = document.getElementById('j_cbAll');
    var j_tbs = document.getElementById('j_tb').querySelectorAll('input');
    j_cbAll.onclick = function () {
      // this.checked 它可以得到当前复选框的选中状态
      for (var i = 0; i < j_tbs.length; i++) {
        j_tbs[i].checked = this.checked;
      }
    }
    for (var i = 0; i < j_tbs.length; i++) {
      j_tbs[i].onclick = function () {
        // flag 控制全选按钮是否都选中
        var flag = true;
        // 每次点击下面的复选框都要循环检查这4个小按钮是否全被选择
        for (var i = 0; i < j_tbs.length; i++) {
          if (!j_tbs[i].checked) {
            flag = false;
            break;  // 可以提高执行效率，只要有一个没有选中就直接退出循环
          }
        }
        j_cbAll.checked = flag;
      }
    }
  </script>
</body>

</html>